<template>
    <div>
        <!-- 查找 -->
        <div class="search">
            <el-input v-model="searchParams.name" style="width: 240px" placeholder="任务名称" clearable />
            <el-button @click="handleSearch" style="margin-left: 10px;">查询</el-button>
            <el-button style="color: white; background-color: #17b3a3; margin-left: 10px;"
                @click="handleAdd">新增</el-button>
            <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
        </div>
        <!-- 表格 -->
        <div class="table">
            <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange"
                v-loading="loading" header-align="center">
                <el-table-column type="selection" width="55" header-align="center" />
                <el-table-column property="code" label="任务编码" width="120" header-align="center" />
                <el-table-column property="name" label="任务名称" width="120" header-align="center" />
                <el-table-column property="createOn" label="创建时间" width="240" header-align="center" />
                <el-table-column property="createBy" label="创建人" header-align="center" />
                <el-table-column property="modifiedOn" label="修改时间" header-align="center" />
                <el-table-column property="modifiedBy" label="修改人" header-align="center" />
                <el-table-column property="remark" label="备注" header-align="center" />
                <el-table-column label="操作" width="180" header-align="center">
                    <template #default="scope">
                        <el-button size="small" @click="handleEdit(scope.row)" link style="color: #17b3a3;">修改</el-button>
                        <el-button size="small" @click="handleDelete(scope.row)" link style="color: #17b3a3;">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 页码 -->
        <div class="pagination">
            <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
                :page-size="pageSize" :current-page="currentPage" :page-sizes="[10, 20, 50, 100]"
                @size-change="handleSizeChange" @current-change="handlePageChange" />
        </div>
        <!-- 新增/编辑窗口 -->
        <el-dialog v-model="dialogFormVisible" :title="formTitle" width="600" @closed="handleResetForm">
            <el-form :model="form" :rules="rules" ref="ruleFormRef" style="margin-left: 20px;" label-width="auto">
                <el-form-item label="任务编码" prop="code" label-position="right">
                    <el-input v-model="form.code" />
                </el-form-item>
                <el-form-item label="任务名称" prop="name" label-position="right">
                    <el-input v-model="form.name" />
                </el-form-item>
                <el-form-item label="备注" label-position="right">
                    <el-input v-model="form.remark" type="textarea" :rows="3" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleConfirm" style="background-color: #17b3a3; color: white;">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { list, add, userdel, detail, updata } from "@/api/biosample-task"
import { ref, reactive, onMounted } from "vue"
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

interface TaskItem {
    id?: number,
    code: string,
    name: string,
    createOn?: string,
    createBy?: string,
    modifiedOn?: string,
    modifiedBy?: string,
    remark: string,
}

const ruleFormRef = ref<FormInstance | null>(null)
const form = reactive<TaskItem>({
    code: '',
    name: '',
    remark: ''
})

const tableData = ref<TaskItem[]>([])
const formTitle = ref('')
const dialogFormVisible = ref(false)
const loading = ref(false)
const selectedRows = ref<TaskItem[]>([])
const currentId = ref<number | null>(null)

const searchParams = reactive({
    name: ''
})

const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)

const rules = reactive<FormRules<TaskItem>>({
    code: [
        { required: true, message: '任务编码不能为空', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '任务名称不能为空', trigger: 'blur' }
    ],
})

const pageParams = reactive({
    page: 1,
    rows: 10,
    name: ''
})

onMounted(() => {
    fetchData()
})

function fetchData() {
    loading.value = true
    list({ ...pageParams, ...searchParams }).then(res => {
        tableData.value = res.page.list
        total.value = res.page.totalCount
        loading.value = false
    }).catch(() => {
        loading.value = false
    })
}

function handleSearch() {
    currentPage.value = 1
    pageParams.page = 1
    fetchData()
}

function handleSizeChange(val: number) {
    pageSize.value = val
    pageParams.rows = val
    fetchData()
}

function handlePageChange(val: number) {
    currentPage.value = val
    pageParams.page = val
    fetchData()
}

function handleSelectionChange(rows: TaskItem[]) {
    selectedRows.value = rows
}

function handleAdd() {
    formTitle.value = "新增"
    dialogFormVisible.value = true
    currentId.value = null
}

// 编辑
function handleEdit(row: TaskItem) {
    formTitle.value = "编辑"
    dialogFormVisible.value = true
    currentId.value = row.id || null

    // 显示加载状态
    loading.value = true

    detail(row.id).then(res => {

        console.log(res, '数据');

        form.code = res.task.code
        form.name = res.task.name
        form.remark = res.task.remark

    })
        .catch(() => {
            ElMessage.error('获取详情失败')
            currentId.value = null
        })
        .finally(() => {
            loading.value = false
        })
}

function handleDelete(row: TaskItem) {
    if (row.id === undefined) {
        ElMessage.error('任务ID未定义');
        return;
    }

    ElMessageBox.confirm(`确定删除这${row.name}任务?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    }).then(() => {
        userdel([row.id]).then(res => {
            console.log(res);
            ElMessage.success('删除成功');
            fetchData();
        }).catch(() => {
            ElMessage.error('删除失败');
        });
    }).catch(() => {
        // 取消删除
    });
}

// 批量删除
function handleBatchDelete() {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的任务')
        return
    }

    const ids = selectedRows.value.map(item => item.id)

    ElMessageBox.confirm(`确定批量删除这${ids.join(',')}任务?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    }).then(() => {
        console.log(11111, '------');
        console.log(ids);
        userdel(ids).then(res => {
            console.log(res);
            ElMessage.success('删除成功')
            fetchData()
        })
    }).catch(() => {
        // 取消删除
    })
}

const handleConfirm = () => {
    if (!ruleFormRef.value) return
    ruleFormRef.value.validate((valid) => {
        if (valid) {
            if (formTitle.value === "新增") {
                add(form).then(() => {
                    ElMessage.success('新增成功')
                    dialogFormVisible.value = false
                    fetchData()
                }).catch(() => {
                    ElMessage.error('新增失败')
                })
            } else {
                if (currentId.value) {
                    updata({ ...form, id: currentId.value }).then(() => {
                        ElMessage.success('修改成功')
                        dialogFormVisible.value = false
                        fetchData()
                    }).catch(() => {
                        ElMessage.error('修改失败')
                    })
                }
            }
        } else {
            ElMessage.error('表单验证失败')
        }
    })
}

function handleResetForm() {
    if (ruleFormRef.value) {
        ruleFormRef.value.resetFields()
        Object.assign(form, {
            code: '',
            name: '',
            remark: ''
        })
        currentId.value = null
    }
}
</script>

<style scoped lang="scss">
.search {
    margin-bottom: 20px;
}

.pagination {
    margin-top: 20px;
    float: right;
}

:deep .table {
  .el-table thead th {
    background-color: #fff !important;
    color: #909399;
  }

  .cell {
    text-align: center !important;
    font-size: 12px !important;
  }
}
</style>
